package com.dragon.mmochat.service;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.message.Mmochat_5_10S;
import com.dragon.mmochat.message.Mmochat_5_1S;
import com.dragon.mmochat.message.Mmochat_5_31S;
import com.dragon.mmochat.message.Mmochat_7_10C;
import com.dragon.mmochat.message.Mmochat_7_15S;
import com.dragon.mmochat.message.Mmochat_7_16C;
import com.dragon.mmochat.message.Mmochat_7_17S;
import com.dragon.mmochat.message.Mmochat_7_18S;
import com.dragon.mmochat.message.Mmochat_7_19S;
import com.dragon.mmochat.message.Mmochat_7_1C;
import com.dragon.mmochat.message.Mmochat_7_20C;
import com.dragon.mmochat.message.Mmochat_7_21S;
import com.dragon.mmochat.message.Mmochat_7_22C;
import com.dragon.mmochat.message.Mmochat_7_23C;
import com.dragon.mmochat.message.Mmochat_7_24C;
import com.dragon.mmochat.message.Mmochat_7_3C;
import com.dragon.mmochat.model.deal.MmochatBorrowRecord;
import com.dragon.mmochat.model.deal.MmochatDeal;
import com.dragon.mmochat.model.deal.MmochatDealPackage;
import com.dragon.mmochat.model.enumType.MmochatDealRoleState;
import com.dragon.mmochat.model.enumType.MmochatDealState;
import com.dragon.mmochat.model.enumType.MmochatObjOwnerState;
import com.dragon.mmochat.model.enumType.MmochatObjectType;
import com.dragon.mmochat.model.enumType.MmochatOtherSystemSettingType;
import com.dragon.mmochat.model.enumType.MmochatPetStateType;
import com.dragon.mmochat.model.enumType.MmochatPropType;
import com.dragon.mmochat.model.enumType.MmochatRoleType;
import com.dragon.mmochat.model.enumType.MmochatServerType;
import com.dragon.mmochat.model.object.MmochatCommonObject;
import com.dragon.mmochat.model.object.MmochatPackageGrid;
import com.dragon.mmochat.model.role.MmochatFriend;
import com.dragon.mmochat.model.role.MmochatPet;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.util.MmochatUtil;
import com.skymobi.handler.SkymobiHandler;
import com.skymobi.message.SkymobiProtocolMessage;
import com.skymobi.message.widget.AddDataTLV;
import com.skymobi.message.widget.ClearDataTLV;
import com.skymobi.message.widget.CreateMsgBoxTLV;
import com.skymobi.message.widget.CtrlTLVStructureRequest;
import com.skymobi.message.widget.SendDataTLV;
import com.skymobi.message.widget.ShowWaitingMsgBoxTLV;

import com.skymobi.service.SkymobiService;
import com.skymobi.util.Text;

public class MmochatDealService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatDealService.class);

	public static Map<Integer, MmochatDeal> deals = new ConcurrentHashMap<Integer, MmochatDeal>();

	// 出借记录，维护后清空:出借者ID-->借方信息列表
	public static Map<Integer, List<MmochatBorrowRecord>> borrowLog = new ConcurrentHashMap<Integer, List<MmochatBorrowRecord>>();

	// 请求开始交易
	public static void startDeal(MmochatPlayer requestDealRole,
			MmochatPlayer targetDealRole) {
		if (requestDealRole == null || targetDealRole == null) {
			return;
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			MmochatUtil.sendCommonMsgbox(requestDealRole, "跨服专区内无法进行交易!");
			return;
		}
		if (requestDealRole.isGuest() || targetDealRole.isGuest()) {
			MmochatUtil.sendCommonMsgbox(requestDealRole, "游客不能参与交易!");
			return;
		}
		MmochatDeal deal = new MmochatDeal();

		synchronized (requestDealRole) {
			if (!requestDealRole.canDeal()) {
				return;
			}
			deal.addDealer(requestDealRole);
		}
		synchronized (targetDealRole) {
			if (!targetDealRole.canDeal()) {
				requestDealRole.setDealId(0);
				MmochatUtil.sendCommonMsgbox(requestDealRole,
						"对方正在交易中,暂时无法与您交易!");
				return;
			}
			deal.addDealer(targetDealRole);
		}
		deals.put(deal.getId(), deal);

		// 发送给请求方
		Mmochat_7_15S pack = new Mmochat_7_15S();
		pack.setDealer(targetDealRole);
		pack.setDealId(deal.getId());
		MmochatUtil.sendCommonPack(requestDealRole, pack);

		// 发送给目标方
		pack = new Mmochat_7_15S();
		pack.setDealer(requestDealRole);
		pack.setDealId(deal.getId());
		MmochatUtil.sendCommonPack(targetDealRole, pack);

		// 互相加为临时好友
		requestDealRole.addTempFriend(targetDealRole);
		targetDealRole.addTempFriend(requestDealRole);

		// 判断是否可能假冒对方好友
		if (!requestDealRole.getMyDearFriends().containsKey(
				targetDealRole.getRoleId())) {
			// targetDealRole不是requestDealRole的好友
			String name = targetDealRole.getName();
			if (name.length() > 1) {
				// 检查targetDealRole的名字与对方好友中的名字，相似度
				int maxSimilar = 0;
				String frdName = "";
				for (MmochatFriend frd : requestDealRole.getMyDearFriends()
						.values()) {
					if (frd != null) {
						int sim = MmochatUtil
								.getSimilarity(name, frd.getName());
						if (sim > maxSimilar) {
							frdName = frd.getName();
							maxSimilar = sim;
						}
					}
				}
				if (maxSimilar > MmochatConstant.warnForDealSimilarity) {
					String msg = "安全提醒：对方不是您的好友，且对方与您的好友"
							+ MmochatUtil.wrapColor(frdName, Color.green) + ""
							+ "名字相似度达" + maxSimilar + "%，请注意对方是否在"
							+ MmochatUtil.wrapColor("假冒您的好友", Color.yellow)
							+ "!";
					msg = MmochatUtil.wrapColor(msg, Color.red);
					MmochatUtil.sendCommonMsgbox(requestDealRole, msg);
				}
			}
		}

		if (!targetDealRole.getMyDearFriends().containsKey(
				requestDealRole.getRoleId())) {
			// requestDealRole不是targetDealRole的好友
			String name = requestDealRole.getName();
			if (name.length() > 1) {
				// 检查requestDealRole的名字与对方好友中的名字，相似度
				int maxSimilar = 0;
				String frdName = "";
				for (MmochatFriend frd : targetDealRole.getMyDearFriends()
						.values()) {
					if (frd != null) {
						int sim = MmochatUtil
								.getSimilarity(name, frd.getName());
						if (sim > maxSimilar) {
							frdName = frd.getName();
							maxSimilar = sim;
						}
					}
				}
				if (maxSimilar > MmochatConstant.warnForDealSimilarity) {
					String msg = "安全提醒：对方不是您的好友，且对方与您的好友"
							+ MmochatUtil.wrapColor(frdName, Color.green) + ""
							+ "名字相似度达" + maxSimilar + "%，请注意对方是否在"
							+ MmochatUtil.wrapColor("假冒您的好友", Color.yellow)
							+ "!";
					msg = MmochatUtil.wrapColor(msg, Color.red);
					MmochatUtil.sendCommonMsgbox(targetDealRole, msg);
				}
			}
		}
	}

	// 7.16 交易提交物品，物品从玩家扣除，放入[交易临时包裹]
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_16(SkymobiHandler handler,
			Mmochat_7_16C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return null;
		}
		MmochatPackageGrid grid = me.getMyPackage().get(req.getGridId());
		if (grid == null || grid.getObject() == null) {
			return null;
		}

		if (!me.isInDeal()) {
			Mmochat_5_1S pack = new Mmochat_5_1S();
			pack.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack);
			return null;
		}
		if (req.getDealId() != me.getDealId()) {
			Mmochat_5_1S pack = new Mmochat_5_1S();
			pack.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack);
			return null;
		}
		MmochatDeal deal = deals.get(me.getDealId());
		if (deal == null) {
			Mmochat_5_1S pack = new Mmochat_5_1S();
			pack.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack);
			return null;
		}
		MmochatDealPackage myDealPack = deal.getReadyTodealMap().get(
				me.getRoleId());
		if (myDealPack == null
				|| myDealPack.getDealState() != MmochatDealRoleState.选择交易物品) {
			Mmochat_5_1S pack = new Mmochat_5_1S();
			pack.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack);
			return null;
		}

		MmochatPackageGrid newGrid = null;
		synchronized (deal) {
			// 需要确保deal未被对方关闭
			if (deal.getDealState() != MmochatDealState.交易中) {
				// 终端已经将这个物品从包裹中删除，需要通知终端增加此物品
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack.addGrid(grid);
				MmochatUtil.sendCommonPack(me, pack);
				return null;
			}

			MmochatCommonObject obj = grid.getObject();
			int dealNum = Math.min(req.getNum(), obj.getOverlapNum());
			if (dealNum <= 0) {
				if (obj.getOverlapNum() <= 0) {
					grid.setObject(null);
				}
				// 下发更新包裹数据
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack.addGrid(grid);
				MmochatUtil.sendCommonPack(me, pack);
				return null;
			}
			MmochatCommonObject newObj = obj.getCloneWithNewId();
			newObj.setOverlapNum(dealNum);
			newGrid = myDealPack.addObjToDealPackage(newObj);
			if (newGrid != null) {
				// 从我的包裹中删除,如果交易失败，这些物品要归还于我
				obj.delOverlapNum(dealNum);
				if (obj.getOverlapNum() <= 0) {
					grid.setObject(null);
				}
				// 下发更新包裹数据
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack.addGrid(grid);
				MmochatUtil.sendCommonPack(me, pack);
			}
		}

		// 通知另一方
		if (newGrid != null) {
			MmochatDealPackage hisPackage = deal.getTheOtherDealPackage(me
					.getRoleId());
			if (hisPackage != null) {
				MmochatPlayer he = MmochatMainService.players.get(hisPackage
						.getRoleId());
				if (he != null) {
					Mmochat_7_17S pack1 = new Mmochat_7_17S();
					pack1.setGrid(newGrid);
					pack1.setDealId(req.getDealId());
					MmochatUtil.sendCommonPack(he, pack1);
				} else {
					// stopDeal是锁定deal的操作，外面不能再有锁定deal,否则死锁
					me.stopDeal();
				}
			} else {
				me.stopDeal();
			}
		}

		return null;
	}

	// 7.22 交易提交宠物，宠物不扣除，复制宠物信息放入[交易临时包裹]
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_22(SkymobiHandler handler,
			Mmochat_7_22C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return null;
		}
		if (!me.isInDeal()) {
			return null;
		}
		if (req.getDealId() != me.getDealId()) {
			return null;
		}
		MmochatDeal deal = deals.get(me.getDealId());
		if (deal == null) {
			return null;
		}
		MmochatDealPackage myDealPack = deal.getReadyTodealMap().get(
				me.getRoleId());
		if (myDealPack == null
				|| myDealPack.getDealState() != MmochatDealRoleState.选择交易物品) {
			return null;
		}
		MmochatPet pet = me.getPetAlongById(req.getPetId());
		if (pet == null) {
			return null;
		}

		String info = "";
		int level = pet.getLevel();
		int blood_protential = (int) (pet.getBlood_protential() * (1 + pet
				.getBloodExtraPercent()));
		int physicalAttack_protential = (int) (pet
				.getPhysicalAttack_protential() * (1 + pet
				.getPhysicalExtraPercent()));
		int magicAttack_protential = (int) (pet.getMagicAttack_protential() * (1 + pet
				.getMagicExtraPercent()));
		int speed_protential = (int) (pet.getSpeed_protential() * (1 + pet
				.getSpeedExtraPercent()));
		int physicalDefend_protential = pet.getPhysicalDefend_protential();
		int magicDefend_protential = pet.getMagicDefend_protential();
		info += MmochatUtil.wrapColor(pet.getPetTypeName() + "(" + level
				+ "级)\n", Color.yellow);
		info += MmochatUtil.wrapColor("气血：" + pet.getTotalBlood() + "\n"
				+ "法力：" + pet.getTotalSprit() + "\n" + "物伤："
				+ pet.getPhysicalAttack() + "\n" + "法伤：" + pet.getSpritAttack()
				+ "\n" + "速度：" + pet.getSpeed() + "\n" + "武学：" + pet.getDao()
				+ "\n", Color.white);
		info += MmochatUtil.wrapColor("成长："
				+ (blood_protential + physicalAttack_protential
						+ magicAttack_protential + speed_protential
						+ physicalDefend_protential + magicDefend_protential)
				+ "\n", Color.cyan);
		info += MmochatUtil.wrapColor("血量成长：" + blood_protential + "\n"
				+ "物攻成长：" + physicalAttack_protential + "\n" + "法攻成长："
				+ magicAttack_protential + "\n" + "速度成长：" + speed_protential
				+ "\n" + "物防成长：" + physicalDefend_protential + "\n" + "法防成长："
				+ magicDefend_protential + "\n", Color.green);
		info += MmochatUtil.wrapColor("属性：未分配(" + pet.getSpace_point() + ")\n",
				Color.cyan);
		info += MmochatUtil.wrapColor("力量 " + pet.getAttack_point() + " 灵力 "
				+ pet.getSprit_point() + " 体力 " + pet.getBlood_point()
				+ " 敏捷  " + pet.getSpeed_point() + "\n", Color.green);
		MmochatCommonObject newObj = new MmochatCommonObject();
		newObj.setObjectType(MmochatObjectType.宠物);
		newObj.setCanOverlap(false);
		newObj.setObjInfo(info);
		newObj.setObjBmpId(pet.getBmpType().getValue());
		newObj.setObjectId(pet.getPetId());
		MmochatPackageGrid newGrid = null;
		synchronized (deal) {
			// 需要确保deal未被对方关闭
			if (deal.getDealState() != MmochatDealState.交易中) {
				return null;
			}
			newGrid = myDealPack.addObjToDealPackage(newObj);
		}
		if (newGrid != null) {
			// 通知另一方
			MmochatDealPackage hisPackage = deal.getTheOtherDealPackage(me
					.getRoleId());
			if (hisPackage != null) {
				MmochatPlayer he = MmochatMainService.players.get(hisPackage
						.getRoleId());
				if (he != null) {
					Mmochat_7_17S pack1 = new Mmochat_7_17S();
					pack1.setGrid(newGrid);
					pack1.setDealId(req.getDealId());
					MmochatUtil.sendCommonPack(he, pack1);
				} else {
					me.stopDeal();
				}
			} else {
				me.stopDeal();
			}
		}
		if (pet.getOwnerState() != MmochatObjOwnerState.未认主) {
			MmochatUtil.sendCommonMsgbox(me,
					"此宠物当前为认主状态，无法交易。请取消本次交易重新再提交，否则将导致本次交易失败。");
			return null;
		}
		return null;
	}

	// 7.1中止交易
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_1(SkymobiHandler handler,
			Mmochat_7_1C req) {
		MmochatPlayer p = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (p == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (!p.isInDeal()) {
			return null;
		}
		if (p.getDealId() != req.getDealId()) {
			return null;
		}
		p.stopDeal();
		return null;
	}

	// 7.20交易金钱，将金钱数额记录到[交易临时包裹]中
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_20(SkymobiHandler handler,
			Mmochat_7_20C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return null;
		}
		if (!me.isInDeal()) {
			return null;
		}
		if (me.getDealId() != req.getDealId()) {
			return null;
		}
		MmochatDeal deal = deals.get(me.getDealId());
		if (deal == null) {
			return null;
		}
		MmochatDealPackage myDealPack = deal.getReadyTodealMap().get(
				me.getRoleId());
		if (myDealPack.getDealState() != MmochatDealRoleState.选择交易物品) {
			return null;
		}
		int small_money = req.getMoney();
		if (small_money < 0) {
			return MmochatUtil.msgbox(req.getHallState(), "金额输入错误!金额不能小于0!");
		}
		MmochatDealPackage myPackage = deal.getReadyTodealMap().get(
				me.getRoleId());
		if (myPackage == null) {
			return null;
		}
		int oldMoney = myPackage.getSmall_money();
		if ((long) Integer.MAX_VALUE - oldMoney < small_money) {
			return MmochatUtil.msgbox(req.getHallState(), "金额超出上限!");
		}
		synchronized (deal) {
			if (myDealPack.getDealState() != MmochatDealRoleState.选择交易物品) {
				return null;
			}
			myPackage.addSmall_money(small_money);
			int curMoney = (int) Math.min(myPackage.getSmall_money(), me
					.getSmall_money());
			if (curMoney < 0) {
				myPackage.setSmall_money(oldMoney);
				return MmochatUtil
						.msgbox(req.getHallState(), "金额输入错误!金额不能小于0!");
			}
			myPackage.setSmall_money(curMoney);
		}
		// 通知对方
		MmochatDealPackage hisPackage = deal.getTheOtherDealPackage(me
				.getRoleId());
		if (hisPackage != null) {
			MmochatPlayer he = MmochatMainService.players.get(hisPackage
					.getRoleId());
			if (he != null) {
				Mmochat_7_21S pack = new Mmochat_7_21S();
				pack.setDealId(req.getDealId());
				pack.setMoney(myPackage.getSmall_money());
				MmochatUtil.sendCommonPack(he, pack);
			} else {
				me.stopDeal();
			}
		} else {
			me.stopDeal();
		}

		return null;
	}

	// 7.10 同意交易
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_10(SkymobiHandler handler,
			Mmochat_7_10C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (!me.isInDeal()) {
			return MmochatUtil.msgbox(req.getHallState(), "本次交易已经取消,请返回!");
		}
		if (me.getDealId() != req.getDealId()) {
			return null;
		}
		MmochatDeal deal = deals.get(me.getDealId());
		if (deal == null) {
			return MmochatUtil.msgbox(req.getHallState(), "本次交易已经取消,请返回!");
		}
		MmochatDealPackage myReadyToDealPackage = deal.getReadyTodealMap().get(
				me.getRoleId());
		if (myReadyToDealPackage == null) {
			return MmochatUtil.msgbox(req.getHallState(), "本次交易已经取消,请返回!");
		}
		MmochatDealPackage hisReadyToDealPackage = deal
				.getTheOtherDealPackage(me.getRoleId());
		if (hisReadyToDealPackage == null) {
			me.stopDeal();
			return MmochatUtil.msgbox(req.getHallState(), "本次交易已经取消,请返回!");
		}
		MmochatPlayer he = MmochatMainService.players.get(hisReadyToDealPackage
				.getRoleId());
		if (he == null) {
			me.stopDeal();
			return MmochatUtil.msgbox(req.getHallState(), "对方掉线,本次交易取消,请返回!");
		}

		if (MmochatNpcService.checkStorePwd(me)) {
			return null;
		}
		
		if (me.isGuest() || he.isGuest()) {
			me.stopDeal();
			return MmochatUtil.msgbox(req.getHallState(), "游客不能参与交易!");
		}

		myReadyToDealPackage.setImei(req.getImei());
		synchronized (deal) {
			if (myReadyToDealPackage.getDealState() == MmochatDealRoleState.确定交易) {
				return MmochatUtil.msgbox(req.getHallState(),
						"您已经同意本次交易,请等待对方的意见!如果您想取消本次交易,请按<取消>键!");
			} else if (myReadyToDealPackage.getDealState() != MmochatDealRoleState.选择交易物品) {
				return MmochatUtil.msgbox(req.getHallState(), "现在不能进行此操作!");
			}
			myReadyToDealPackage.setDealState(MmochatDealRoleState.确定交易);
			if (!deal.isAllConfirmed()) {
				// 通知另一方
				Mmochat_7_19S pack = new Mmochat_7_19S();
				pack.setMsg("对方已点<同意交易>!");
				pack.setDealId(req.getDealId());
				MmochatUtil.sendCommonPack(he, pack);
				return null;
			}
		}

		synchronized (deal) {
			// 交易开始，锁定交易状态为无法取消交易
			if (deal.getDealState() == MmochatDealState.交易中) {
				deal.setDealState(MmochatDealState.交易不可取消);
			} else {
				return null;
			}
		}

		boolean hasPet = false;
		// 交易物品
		List<MmochatPackageGrid> myGirdsNeedUpdate = new ArrayList<MmochatPackageGrid>();
		List<MmochatPackageGrid> hisGirdsNeedUpdate = new ArrayList<MmochatPackageGrid>();
		String myDealObjInfo = "", hisDealObjInfo = "";
		String myDealPackLog = myReadyToDealPackage.getDealLog();
		String hisDealPackLog = hisReadyToDealPackage.getDealLog();
		// 记录下交易前双方的金钱，并将金钱给对方，如果对方金钱超过上限，则恢复原有的金钱，
		// 则设置状态为可以取消交易，并跳到失败处理。
		if (me.getSmall_money() < myReadyToDealPackage.getSmall_money()) {
			// 我的金钱已不足，可能在赌场输了，交易取消
			deal.setDealState(MmochatDealState.交易已取消);
			deal.failedDeal(me.getRoleId(), he.getRoleId());

			Mmochat_7_18S pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("您的金钱不足，交易失败!");
			MmochatUtil.sendCommonPack(me, pack);

			pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("对方金钱不足，交易失败!");
			MmochatUtil.sendCommonPack(he, pack);
			return null;
		}
		if (he.getSmall_money() < hisReadyToDealPackage.getSmall_money()) {
			// 对方的金钱已不足，可能在赌场输了，交易取消
			deal.setDealState(MmochatDealState.交易已取消);
			deal.failedDeal(me.getRoleId(), he.getRoleId());

			Mmochat_7_18S pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("对方的金钱不足，交易失败!");
			MmochatUtil.sendCommonPack(me, pack);

			pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("您的金钱不足，交易失败!");
			MmochatUtil.sendCommonPack(he, pack);
			return null;
		}
		long myRestMoney = (long) me.getSmall_money()
				- (long) myReadyToDealPackage.getSmall_money()
				+ (long) hisReadyToDealPackage.getSmall_money();
		if (myRestMoney > Integer.MAX_VALUE) {
			// 金钱超过上限
			deal.setDealState(MmochatDealState.交易已取消);
			deal.failedDeal(me.getRoleId(), he.getRoleId());

			Mmochat_7_18S pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("您包裹中金钱过多，无法再增加对方交易给您的金钱数额,本次交易失败!");
			MmochatUtil.sendCommonPack(me, pack);

			pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("对方包裹中金钱过多，无法再增加对方交易给您的金钱数额,本次交易失败!");
			MmochatUtil.sendCommonPack(he, pack);
			return null;
		}
		long hisRestMoney = (long) he.getSmall_money()
				- (long) hisReadyToDealPackage.getSmall_money()
				+ (long) myReadyToDealPackage.getSmall_money();
		if (hisRestMoney > Integer.MAX_VALUE) {
			// 金钱超过上限
			deal.setDealState(MmochatDealState.交易已取消);
			deal.failedDeal(me.getRoleId(), he.getRoleId());

			Mmochat_7_18S pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("对方包裹中金钱过多，无法再增加对方交易给您的金钱数额,本次交易失败!");
			MmochatUtil.sendCommonPack(me, pack);

			pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("您包裹中金钱过多，无法再增加对方交易给您的金钱数额,本次交易失败!");
			MmochatUtil.sendCommonPack(he, pack);
			return null;
		}

		// 出借装备、法宝、宠物，都是不可叠加的
		boolean IBorrowFromHim = false, HeBorrowFromMe = false;
		// 我借给他的东西、宠物
		List<MmochatCommonObject> objsHeBorrowFromMe = new ArrayList<MmochatCommonObject>();
		List<MmochatPet> petsHeBorrowFromMe = new ArrayList<MmochatPet>();

		// 他借给我的东西、宠物
		List<MmochatCommonObject> objsIBorrowFromHim = new ArrayList<MmochatCommonObject>();
		List<MmochatPet> petsIBorrowFromHim = new ArrayList<MmochatPet>();

		// 对于不可交易物品的检测
		for (MmochatPackageGrid grid : myReadyToDealPackage
				.getMyDealPackageGrids().values()) {
			MmochatCommonObject obj = grid.getObject();
			if (obj == null) {
				continue;
			}
			if (obj.getObjectType() == MmochatObjectType.宠物) {
				MmochatPet pet = me.getPetAlongById(obj.getId());
				if (pet != null) {
					if (pet.getOwnerState() != MmochatObjOwnerState.未认主) {
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("您提交的宠物中，有尚在<认主状态>的宠物，本次交易无法进行!");
						MmochatUtil.sendCommonPack(me, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("对方提交的宠物中，有尚在<认主状态>的宠物，本次交易无法进行!");
						MmochatUtil.sendCommonPack(he, pack);
						return null;
					}

					// 借来的宠物只能交易给出借者
					if (pet.getBorrowFromRoleId() != null
							&& pet.getBorrowFromRoleId() != he.getRoleId()) {
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("您提交的宠物中，有向他人借来的宠物，此宠物不能交易给其它人，只能归还原主人!");
						MmochatUtil.sendCommonPack(me, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("对方提交的宠物中，有向他人借来的宠物，无法交易给您!");
						MmochatUtil.sendCommonPack(he, pack);
						return null;
					}
				}
			} else {
				if (!obj.isCanDeal()) {
					deal.setDealState(MmochatDealState.交易已取消);
					deal.failedDeal(me.getRoleId(), he.getRoleId());

					Mmochat_7_18S pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("您提交的物品中，有不允许交易的物品，本次交易无法进行!");
					MmochatUtil.sendCommonPack(me, pack);

					pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("对方提交的物品中，有不允许交易的物品，本次交易无法进行!");
					MmochatUtil.sendCommonPack(he, pack);
					return null;
				}

				// 借来的物品只能交易给出借者
				if (obj.getBorrowFromRoleId() != null
						&& obj.getBorrowFromRoleId() != he.getRoleId()) {
					deal.setDealState(MmochatDealState.交易已取消);
					deal.failedDeal(me.getRoleId(), he.getRoleId());

					Mmochat_7_18S pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("您提交的物品中，有向他人借来的物品，此物品不能交易给其它人，只能归还原主人!");
					MmochatUtil.sendCommonPack(me, pack);

					pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("对方提交的物品中，有向他人借来的物品，无法交易给您!");
					MmochatUtil.sendCommonPack(he, pack);
					return null;
				}

				// 给出借条
				if (obj.getPropType() != null
						&& obj.getPropType() == MmochatPropType.借条) {
					if (!MmochatConstant.allowedBorrow) {
						// 合服前3天，不允许出借
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("本区在近期可能会进行合区，暂停借条使用!");
						MmochatUtil.sendCommonPack(me, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("本区在近期可能会进行合区，暂停借条使用!");
						MmochatUtil.sendCommonPack(he, pack);
						return null;
					}
					IBorrowFromHim = true;
				}
			}
		}

		for (MmochatPackageGrid grid : hisReadyToDealPackage
				.getMyDealPackageGrids().values()) {
			MmochatCommonObject obj = grid.getObject();
			if (obj == null) {
				continue;
			}
			if (obj.getObjectType() == MmochatObjectType.宠物) {
				MmochatPet pet = he.getPetAlongById(obj.getId());
				if (pet != null) {
					if (pet.getOwnerState() != MmochatObjOwnerState.未认主) {
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("您提交的宠物中，有尚在<认主状态>的宠物，本次交易无法进行!");
						MmochatUtil.sendCommonPack(he, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("对方提交的宠物中，有尚在<认主状态>的宠物，本次交易无法进行!");
						MmochatUtil.sendCommonPack(me, pack);
						return null;
					}

					// 借来的东西只能交易给原主人
					if (pet.getBorrowFromRoleId() != null
							&& pet.getBorrowFromRoleId() != me.getRoleId()) {
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("您提交的宠物中，有向他人借来的宠物，此宠物不能交易给其它人，只能归还原主人!");
						MmochatUtil.sendCommonPack(he, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("对方提交的宠物中，有向他人借来的宠物，无法交易给您!");
						MmochatUtil.sendCommonPack(me, pack);
						return null;

					}
				}
			} else {
				if (!obj.isCanDeal()) {
					deal.setDealState(MmochatDealState.交易已取消);
					deal.failedDeal(me.getRoleId(), he.getRoleId());

					Mmochat_7_18S pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("您提交的物品中，有不允许交易的物品，本次交易无法进行!");
					MmochatUtil.sendCommonPack(he, pack);

					pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("对方提交的物品中，有不允许交易的物品，本次交易无法进行!");
					MmochatUtil.sendCommonPack(me, pack);
					return null;
				}

				// 借来的东西只能交易给原主人
				if (obj.getBorrowFromRoleId() != null
						&& obj.getBorrowFromRoleId() != me.getRoleId()) {
					deal.setDealState(MmochatDealState.交易已取消);
					deal.failedDeal(me.getRoleId(), he.getRoleId());

					Mmochat_7_18S pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("您提交的物品中，有向他人借来的物品，此物品不能交易给其它人，只能归还原主人!");
					MmochatUtil.sendCommonPack(he, pack);

					pack = new Mmochat_7_18S();
					pack.setDealId(req.getDealId());
					pack.setMsg("对方提交的物品中，有向他人借来的物品，无法交易给您!");
					MmochatUtil.sendCommonPack(me, pack);
					return null;

				}

				// 给出借条
				if (obj.getPropType() != null
						&& obj.getPropType() == MmochatPropType.借条) {
					if (!MmochatConstant.allowedBorrow) {
						// 合服前3天，不允许出借
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("本区在近期可能会进行合区，暂停借条使用!");
						MmochatUtil.sendCommonPack(he, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("本区在近期可能会进行合区，暂停借条使用!");
						MmochatUtil.sendCommonPack(me, pack);
						return null;
					}
					HeBorrowFromMe = true;
				}
			}
		}

		// 正式开始交易
		try {
			boolean success = true;

			for (MmochatPackageGrid grid : myReadyToDealPackage
					.getMyDealPackageGrids().values()) {
				MmochatCommonObject obj = grid.getObject();
				if (obj == null) {
					continue;
				}
				// 宠物的处理
				String myErrMsg = "", hisErrMsg = "";
				if (obj.getObjectType() == MmochatObjectType.宠物) {
					// 遍历[交易临时包裹]，将宠物一个一个先增加给对方，
					// 如果宠物已满交易失败，则设置状态为可以取消交易，则跳到失败处理；
					// 交易成功则将宠物从本方扣除，并将宠物记录到[已交易物品列表]。
					hasPet = true;
					MmochatPet pet = me.getPetAlongById(obj.getId());
					if (pet == null) {
						success = false;
						myErrMsg = "您交易的宠物未找到,交易失败!";
						hisErrMsg = "对方交易的宠物未找到,交易失败!";
					} else {
						// if (pet.getLevel() >= he.getLevel()
						// + MmochatConstant.maxPetLevelMoreThanOwner) {
						// success = false;
						// myErrMsg = "您交易的宠物等级超过对方等级"
						// + MmochatConstant.maxPetLevelMoreThanOwner
						// + "级,交易失败!";
						// hisErrMsg = "对方交易的宠物等级超过您等级"
						// + MmochatConstant.maxPetLevelMoreThanOwner
						// + "级,交易失败!";
						// } else if (pet.getOwnerLevelNeed() > he.getLevel()) {
						// success = false;
						// myErrMsg = "对方等级不足以携带您交易的宠物,交易失败!";
						// hisErrMsg = "您的等级不足以携带对方交易的宠物,交易失败!";
						// } else
						if (he.isPetFull()) {
							success = false;
							myErrMsg = "对方携带的宠物数量已达上限,交易失败!";
							hisErrMsg = "您携带的宠物数量已达上限,交易失败!";
						} else {
							success = he.addPet(pet);
						}
					}
					if (!success) {
						// 包裹空间不足
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg(myErrMsg);
						MmochatUtil.sendCommonPack(me, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg(hisErrMsg);
						MmochatUtil.sendCommonPack(he, pack);
						return null;
					} else {
						hasPet = true;
						me.delPet(obj.getId());
						deal.addMyGivenPet(me.getRoleId(), pet);
						pet.setState(MmochatPetStateType.休息);

						myDealObjInfo += "1个" + pet.getPetTypeName();
						// 我借给他的东西
						if (pet.getBorrowFromRoleId() != null
								&& pet.getBorrowFromRoleId() == he.getRoleId()) {
							petsHeBorrowFromMe.add(pet);
							myDealObjInfo += "(还)";
						} else if (HeBorrowFromMe) {
							petsHeBorrowFromMe.add(pet);
							myDealObjInfo += "(借)";
						}
						myDealObjInfo += ",";
					}
				} else {
					// 遍历[交易临时包裹]，将物品复制一份，
					// 并增加给对方(此时由于叠加操作可能导致物品被分割而改变物品属性，
					// 故使用复制品，以免影响[交易临时包裹]中的物品属性)，
					// 如果包裹已满交易失败，则设置状态为可以取消交易，则跳到失败处理；
					// 交易成功则将此物品添加到[已交易物品列表]。
					int num = obj.getOverlapNum();
					if (he.calRestPackageSpace(obj.getType(), obj
							.isCanOverlap(), obj.isCanDeal()) < num) {
						// 包裹空间不足
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("对方包裹空间不足,交易失败!");
						MmochatUtil.sendCommonPack(me, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("您的包裹空间不足,交易失败!");
						MmochatUtil.sendCommonPack(he, pack);
						return null;
					} else {
						if (obj.getPropType() != null
								&& obj.getPropType() == MmochatPropType.借条) {
							// 借条消失
							deal.addMyGivenObj(me.getRoleId(), obj);
						} else {
							MmochatCommonObject objCopy = obj.getClone();
							List<MmochatPackageGrid> grids = he
									.addObjectToPackage(objCopy, false);
							hisGirdsNeedUpdate.addAll(grids);

							deal.addMyGivenObj(me.getRoleId(), obj);
							myDealObjInfo += num + "个" + obj.getName();

							if (obj.getBorrowFromRoleId() != null
									&& obj.getBorrowFromRoleId() == he
											.getRoleId()) {
								objsHeBorrowFromMe.add(objCopy);
								myDealObjInfo += "(还)";
							} else if (HeBorrowFromMe && obj.canBorrow()) {
								objsHeBorrowFromMe.add(objCopy);
								myDealObjInfo += "(借)";
							}
							myDealObjInfo += ",";
						}
					}
				}
			}

			for (MmochatPackageGrid grid : hisReadyToDealPackage
					.getMyDealPackageGrids().values()) {
				MmochatCommonObject obj = grid.getObject();
				if (obj == null) {
					continue;
				}
				// 宠物的处理
				String myErrMsg = "", hisErrMsg = "";
				if (obj.getObjectType() == MmochatObjectType.宠物) {
					// 遍历[交易临时包裹]，将宠物一个一个先增加给对方，
					// 如果宠物已满交易失败，则设置状态为可以取消交易，则跳到失败处理；
					// 交易成功则将宠物从本方扣除，并将宠物记录到[已交易物品列表]。
					hasPet = true;
					MmochatPet pet = he.getPetAlongById(obj.getId());
					if (pet == null) {
						success = false;
						myErrMsg = "您交易的宠物未找到,交易失败!";
						hisErrMsg = "对方交易的宠物未找到,交易失败!";
						// } else if (pet.getOwnerLevelNeed() > me.getLevel()) {
						// success = false;
						// myErrMsg = "对方等级不足以携带您交易的宠物,交易失败!";
						// hisErrMsg = "您的等级不足以携带对方交易的宠物,交易失败!";
					} else {
						// if (pet.getLevel() >= me.getLevel()
						// + MmochatConstant.maxPetLevelMoreThanOwner) {
						// success = false;
						// myErrMsg = "您交易的宠物等级超过对方等级"
						// + MmochatConstant.maxPetLevelMoreThanOwner
						// + "级,交易失败!";
						// hisErrMsg = "对方交易的宠物等级超过您等级"
						// + MmochatConstant.maxPetLevelMoreThanOwner
						// + "级,交易失败!";
						// } else

						if (me.isPetFull()) {
							success = false;
							myErrMsg = "对方携带的宠物数量已达上限,交易失败!";
							hisErrMsg = "您携带的宠物数量已达上限,交易失败!";
						} else {
							success = me.addPet(pet);
						}
					}
					if (!success) {
						// 包裹空间不足
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg(hisErrMsg);
						MmochatUtil.sendCommonPack(me, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg(myErrMsg);
						MmochatUtil.sendCommonPack(he, pack);
						return null;
					} else {
						hasPet = true;
						he.delPet(obj.getId());
						deal.addMyGivenPet(he.getRoleId(), pet);
						pet.setState(MmochatPetStateType.休息);
						hisDealObjInfo += "1个" + pet.getPetTypeName();
						// 我向他借的东西
						if (pet.getBorrowFromRoleId() != null
								&& pet.getBorrowFromRoleId() == me.getRoleId()) {
							petsIBorrowFromHim.add(pet);
							hisDealObjInfo += "(还)";
						} else if (IBorrowFromHim) {
							petsIBorrowFromHim.add(pet);
							hisDealObjInfo += "(借)";
						}
						hisDealObjInfo += ",";
					}
				} else {
					// 遍历[交易临时包裹]，将物品复制一份，
					// 并增加给对方(此时由于叠加操作可能导致物品被分割而改变物品属性，故使用复制品，
					// 以免影响[交易临时包裹]中的物品属性)，
					// 如果包裹已满交易失败，则设置状态为可以取消交易，则跳到失败处理；
					// 交易成功则将此物品添加到[已交易物品列表]。
					int num = obj.getOverlapNum();
					if (me.calRestPackageSpace(obj.getType(), obj
							.isCanOverlap(), obj.isCanDeal()) < num) {
						// 包裹空间不足
						deal.setDealState(MmochatDealState.交易已取消);
						deal.failedDeal(me.getRoleId(), he.getRoleId());

						Mmochat_7_18S pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("对方包裹空间不足,交易失败!");
						MmochatUtil.sendCommonPack(he, pack);

						pack = new Mmochat_7_18S();
						pack.setDealId(req.getDealId());
						pack.setMsg("您的包裹空间不足,交易失败!");
						MmochatUtil.sendCommonPack(me, pack);

						return null;
					} else {
						if (obj.getPropType() != null
								&& obj.getPropType() == MmochatPropType.借条) {
							// 借条消失
							deal.addMyGivenObj(he.getRoleId(), obj);
						} else {
							MmochatCommonObject objCopy = obj.getClone();
							List<MmochatPackageGrid> grids = me
									.addObjectToPackage(objCopy, false);
							myGirdsNeedUpdate.addAll(grids);
							deal.addMyGivenObj(he.getRoleId(), obj);
							hisDealObjInfo += num + "个" + obj.getName();

							// 我向他借的东西
							if (obj.getBorrowFromRoleId() != null
									&& obj.getBorrowFromRoleId() == me
											.getRoleId()) {
								objsIBorrowFromHim.add(objCopy);
								hisDealObjInfo += "(还)";
							} else if (IBorrowFromHim && obj.canBorrow()) {
								objsIBorrowFromHim.add(objCopy);
								hisDealObjInfo += "(借)";
							}
							hisDealObjInfo += ",";
						}
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			// 交易过程中任何情况下，执行了停止交易或交易出异常，则设置状态为取消交易，并跳到失败处理
			deal.setDealState(MmochatDealState.交易已取消);
			deal.failedDeal(me.getRoleId(), he.getRoleId());

			Mmochat_7_18S pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("出现异常,本次交易失败!");
			MmochatUtil.sendCommonPack(me, pack);

			pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("出现异常,本次交易失败!");
			MmochatUtil.sendCommonPack(he, pack);
			return null;
		}

		// 出借信息处理
		try {
			// 我向他借东西
			for (MmochatCommonObject obj : objsIBorrowFromHim) {
				if (obj.canBorrow()) {
					if (obj.getBorrowFromRoleId() != null
							&& obj.getBorrowFromRoleId() == me.getRoleId()) {
						// 物归原主
						obj.setBorrowFromRoleId(null);
					} else if (obj.getBorrowFromRoleId() == null) {
						// 向他借
						obj.setBorrowFromRoleId(he.getRoleId());
					}
				}
			}
			for (MmochatPet pet : petsIBorrowFromHim) {
				if (pet.getBorrowFromRoleId() != null
						&& pet.getBorrowFromRoleId() == me.getRoleId()) {
					// 物归原主
					pet.setBorrowFromRoleId(null);
				} else if (pet.getBorrowFromRoleId() == null) {
					// 向他借
					pet.setBorrowFromRoleId(he.getRoleId());
				}
			}

			// 他向我借东西
			for (MmochatCommonObject obj : objsHeBorrowFromMe) {
				if (obj.canBorrow()) {
					if (obj.getBorrowFromRoleId() != null
							&& obj.getBorrowFromRoleId() == he.getRoleId()) {
						// 物归原主
						obj.setBorrowFromRoleId(null);
					} else if (obj.getBorrowFromRoleId() == null) {
						// 向他借
						obj.setBorrowFromRoleId(me.getRoleId());
					}
				}
			}
			for (MmochatPet pet : petsHeBorrowFromMe) {
				if (pet.getBorrowFromRoleId() != null
						&& pet.getBorrowFromRoleId() == he.getRoleId()) {
					// 物归原主
					pet.setBorrowFromRoleId(null);
				} else if (pet.getBorrowFromRoleId() == null) {
					// 向他借
					pet.setBorrowFromRoleId(me.getRoleId());
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// 出借信息记录
		try {
			if (IBorrowFromHim) {
				// 我向他借
				List<MmochatBorrowRecord> list = borrowLog.get(he.getRoleId());
				if (list == null) {
					list = new ArrayList<MmochatBorrowRecord>();
					borrowLog.put(he.getRoleId(), list);
				}
				boolean has = false;
				for (MmochatBorrowRecord r : list) {
					if (r.getBorrowId() == me.getRoleId()) {
						// 更新最后出借时间
						r.setTime(System.currentTimeMillis());
						has = true;
						break;
					}
				}
				if (!has) {
					MmochatBorrowRecord r = new MmochatBorrowRecord();
					r.setBorrowId(me.getRoleId());
					r.setName(me.getName());
					list.add(r);
				}
			} else if (HeBorrowFromMe) {
				// 他向我借
				List<MmochatBorrowRecord> list = borrowLog.get(me.getRoleId());
				if (list == null) {
					list = new ArrayList<MmochatBorrowRecord>();
					borrowLog.put(me.getRoleId(), list);
				}
				boolean has = false;
				for (MmochatBorrowRecord r : list) {
					if (r.getBorrowId() == he.getRoleId()) {
						// 更新最后出借时间
						r.setTime(System.currentTimeMillis());
						has = true;
						break;
					}
				}
				if (!has) {
					MmochatBorrowRecord r = new MmochatBorrowRecord();
					r.setBorrowId(he.getRoleId());
					r.setName(he.getName());
					list.add(r);
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// 执行数据库操作，交易金钱并保存双方的包裹和宠物数据。
		// 如果数据库操作异常，则跳到失败处理
		try {
			// myPackage中的物品信息在上述交易中已经更改，故使用事先保存的myDealPackLog和hisDealPackLog
			MmochatDao.makeDeal(me, myReadyToDealPackage.getSmall_money(),
					myReadyToDealPackage.getImei(), myDealPackLog, he,
					hisReadyToDealPackage.getSmall_money(),
					hisReadyToDealPackage.getImei(), hisDealPackLog);

			try {
				if (myReadyToDealPackage.getSmall_money() > 0) {
					myDealObjInfo += MmochatUtil
							.getColorMoney(myReadyToDealPackage
									.getSmall_money())
							+ "文钱,";
				}
				if (hisReadyToDealPackage.getSmall_money() > 0) {
					hisDealObjInfo += MmochatUtil
							.getColorMoney(hisReadyToDealPackage
									.getSmall_money())
							+ "文钱,";
				}

				String myDealInfo = "", hisDealInfo = "";
				if (myDealObjInfo != "") {
					myDealInfo += "你交易给"
							+ MmochatUtil.wrapColor(he.getName(), Color.yellow)
							+ ":";
					myDealInfo += myDealObjInfo + "交易成功。";

					hisDealInfo += MmochatUtil.wrapColor(me.getName(),
							Color.yellow)
							+ "交易给你:" + myDealObjInfo + "交易成功。";
				}
				if (hisDealObjInfo != "") {
					myDealInfo += MmochatUtil.wrapColor(he.getName(),
							Color.yellow)
							+ "交易给你:";
					myDealInfo += hisDealObjInfo + "交易成功。";

					hisDealInfo = "你交易给"
							+ MmochatUtil.wrapColor(me.getName(), Color.yellow)
							+ ":" + hisDealObjInfo + "交易成功。" + hisDealInfo;
				}
				if (myDealInfo != "") {
					MmochatChatService.sendSystemMsgToPerson(me, myDealInfo);
				}
				if (hisDealInfo != "") {
					MmochatChatService.sendSystemMsgToPerson(he, hisDealInfo);
				}
				if (hasPet) {
					// 更新宠物信息
					Mmochat_5_10S pack = new Mmochat_5_10S();
					pack.setReset(true);
					pack.setPets(new ArrayList<MmochatPet>(me.getPets()
							.values()));
					MmochatUtil.sendCommonPack(me, pack);

					pack.setPets(new ArrayList<MmochatPet>(he.getPets()
							.values()));
					MmochatUtil.sendCommonPack(he, pack);
				}

				// 更新包裹游戏币
				Mmochat_5_31S moneyPack = new Mmochat_5_31S();
				moneyPack.setSmallMoney((int) me.getSmall_money());
				MmochatUtil.sendCommonPack(me, moneyPack);

				moneyPack = new Mmochat_5_31S();
				moneyPack.setSmallMoney((int) he.getSmall_money());
				MmochatUtil.sendCommonPack(he, moneyPack);

				Mmochat_7_18S pack = new Mmochat_7_18S();
				pack.setDealId(req.getDealId());
				pack.setMsg("交易成功!");

				MmochatUtil.sendCommonPack(me, pack);
				MmochatUtil.sendCommonPack(he, pack);

				Mmochat_5_1S gridPack = new Mmochat_5_1S();
				gridPack.setGrids(myGirdsNeedUpdate);
				MmochatUtil.sendCommonPack(me, gridPack);

				gridPack = new Mmochat_5_1S();
				gridPack.setGrids(hisGirdsNeedUpdate);
				MmochatUtil.sendCommonPack(he, gridPack);

				// 设置交易状态为已交易完成并解锁
				deal.finishDeal();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// 如果交易失败,需要重设用户信息
			deal.setDealState(MmochatDealState.交易已取消);

			Mmochat_7_18S pack = new Mmochat_7_18S();
			pack.setDealId(req.getDealId());
			pack.setMsg("服务器忙,本次交易失败!");

			MmochatUtil.sendCommonPack(me, pack);
			MmochatUtil.sendCommonPack(he, pack);
			deal.failedDeal(me.getRoleId(), he.getRoleId());
		}
		return null;
	}

	// 申请远程交易
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_23(SkymobiHandler handler,
			Mmochat_7_23C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return null;
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			return MmochatUtil.msgbox(req.getHallState(), "跨服专区内无法进行此操作!");
		}
		if (!me.getOtherSystemSettingByType(MmochatOtherSystemSettingType.远程交易)) {
			return MmochatUtil.msgbox(req.getHallState(),
					"您设置了拒绝远程交易!请按左软键->其它系统设置中进行开启。");
		}

		if (me.getRoleId() == req.getTargetRoleId()) {
			return MmochatUtil.msgbox(req.getHallState(), "不能与自己进行交易!");
		}
		long interval = System.currentTimeMillis()
				- me.getLastTimeOfRemoteDeal();
		if (interval < MmochatConstant.minIntervalOfRemoteDeal) {
			int sec = (int) (MmochatConstant.minIntervalOfRemoteDeal / MmochatConstant.MS_PER_SECOND);
			int rest = (int) ((MmochatConstant.minIntervalOfRemoteDeal - interval) / MmochatConstant.MS_PER_SECOND);
			return MmochatUtil.msgbox(req.getHallState(), "远程交易请求每隔" + sec
					+ "秒可以发出一次，请再过" + rest + "秒再试。");
		}
		MmochatPlayer he = MmochatMainService.players
				.get(req.getTargetRoleId());
		if (he == null) {
			return MmochatUtil.msgbox(req.getHallState(), "对方已下线!");
		}
		if (!he.getOtherSystemSettingByType(MmochatOtherSystemSettingType.远程交易)) {
			return MmochatUtil.msgbox(req.getHallState(), "对方设置了拒绝远程交易!");
		}
		me.setLastTimeOfRemoteDeal(System.currentTimeMillis());

		// 下发交易请求
		String msg = MmochatUtil.wrapColor(me.getName(), Color.green) + "("
				+ me.getLevel() + "级)请求与您进行"
				+ MmochatUtil.wrapColor("远程交易", Color.yellow) + "!";
		CreateMsgBoxTLV msgbox = new CreateMsgBoxTLV();
		msgbox.setContent(new Text(msg));
		msgbox.setLeftName("同意");
		msgbox.setRightName("拒绝");

		msgbox.addLeftTLV(new ClearDataTLV());
		msgbox.addLeftTLV(new AddDataTLV((int) me.getRoleId()));
		msgbox.addLeftTLV(new AddDataTLV((int) he.getRoleId()));
		msgbox.addLeftTLV(new SendDataTLV(MmochatConstant.getClientModuleId(),
				MmochatMain.getModuleInstID(),
				MmochatConstant.MSGCODE_MMOCHAT_C_6_1, (int) 2));

		msgbox.addRightTLV(new ClearDataTLV());
		msgbox.addRightTLV(new AddDataTLV((int) he.getRoleId()));
		msgbox.addRightTLV(new SendDataTLV(MmochatConstant.getClientModuleId(),
				MmochatMain.getModuleInstID(),
				MmochatConstant.MSGCODE_MMOCHAT_C_7_24, (int) me.getRoleId()));

		CtrlTLVStructureRequest pack = new CtrlTLVStructureRequest(0, msgbox);
		pack.setSrcId(MmochatMain.getModuleInstID());
		pack.setDstId(MmochatConstant.getClientModuleId());
		pack.setMsgCode(MmochatConstant.MSGCODE_MMOCHAT_S_10_20);
		MmochatUtil.sendCommonPack(he, pack);

		return MmochatUtil.msgbox(req.getHallState(), "交易请求已发出!");
	}

	// 拒绝远程交易
	@SkymobiService
	public SkymobiProtocolMessage handleC_7_24(SkymobiHandler handler,
			Mmochat_7_24C req) {
		MmochatPlayer he = MmochatMainService.players
				.get(req.getTargetRoleId());
		if (he == null) {
			return null;
		}

		MmochatPlayer me = MmochatMainService.players.get(req.getRoleId());
		if (me == null) {
			MmochatChatService.sendSystemMsgToPerson(he, "对方拒绝了您的交易请求!");
		} else {
			MmochatChatService.sendSystemMsgToPerson(he, MmochatUtil.wrapColor(
					me.getName(), Color.green)
					+ "拒绝了您的交易请求!");
		}
		return null;
	}
}